import { contextBridge, ipcRenderer } from 'electron'
import type { IpcRendererEvent } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const api = {
  selectMultiFile: () => {
    return ipcRenderer.invoke('selectMultiFile')
  },
  selectMultiFolder: () => {
    return ipcRenderer.invoke('selectMultiFolder')
  },
  selectSingleFolder: async () => {
    return ipcRenderer.invoke('selectSingleFolder')
  },
  convertPathsToTableData: (pathList: string[], flag: 'file' | 'folder') => {
    return ipcRenderer.invoke('convertPathsToTableData', pathList, flag)
  },
  openPath: (path: string) => {
    return ipcRenderer.invoke('openPath', path)
  },
  // 选择 Excel 文件
  importExcel: (defaultPath: string | undefined) => {
    return ipcRenderer.invoke('importExcel', defaultPath)
  },
  // 选择 Excel 中某个 Sheet
  selectExcelSheet: (
    loadDialog: (sheetNames: string[]) => Promise<string | undefined>,
    getExcelInitialData: (excelInitialData: IExcelInitialData) => void
  ) => {
    ipcRenderer.on(
      'selectExcelSheet',
      async (
        _event: IpcRendererEvent,
        sheetNames: string[],
        result: IExcelInitialData
      ) => {
        const checkedSheetName = await loadDialog(sheetNames)
        // 如果选择了 Sheet
        if (checkedSheetName) {
          // 解析 Excel 数据
          const excelFileContent = await ipcRenderer.invoke(
            'parseExcelToJSON',
            result.fullPath,
            checkedSheetName
          )

          result.excelFileContent = excelFileContent

          getExcelInitialData(result)
        }
      }
    )
  },
  // 执行文件 / 目录重命名
  executeFileRename: (
    tableData: ITableDataItem[],
    saveMethod: '0' | '1' | '2',
    targetDir: string | undefined
  ) => {
    return ipcRenderer.invoke(
      'executeFileRename',
      tableData,
      saveMethod,
      targetDir
    )
  },
  // 获取默认文件存储目录
  getAppSaveDir: () => {
    return ipcRenderer.invoke('getAppSaveDir')
  },
  // 确保目录一定存在,如果不存在则创建
  ensureDir: (dirPath: string) => {
    return ipcRenderer.invoke('ensureDir', dirPath)
  },
  minimize: () => {
    ipcRenderer.send('minimize')
  },
  maximize: () => {
    ipcRenderer.send('maximize')
  },
  close: () => {
    ipcRenderer.send('close')
  }
}

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
